import React, { useEffect } from "react";
import sdk from "qcloud-iotexplorer-h5-panel-sdk";
import {
  HeadBoolPanel,
  HeadEnumPanel,
  HeadNumberPanel,
} from "../components/HeadPanels";
import { useDeviceData } from "../hooks/useDeviceData";
import { StandardBleConnector } from "../StandardBleDemo/components/StandardBleConnector";
import { DeviceDetailBtn } from "./DeviceDetailBtn";
import { PropertyCard } from "./PropertyCard";
import { DataTemplateProperty } from "../dataTemplate";
import "./DevicePanel.less";

const windowHeight =
  window.innerHeight || document.documentElement.clientHeight;

var g_value = 0;

export function DevicePanel() {
  const [state, { onDeviceDataChange, onDeviceStatusChange }] = useDeviceData(
    sdk
  );

  const isStandardBleDevice = sdk.isStandardBleDevice;

  // WebSocket 监听
  useEffect(() => {
    const handleWsControl = ({ deviceId, deviceData }: {
      deviceId: string;
      deviceData: Record<string, { Value: unknown; LastUpdate: number }>;
    }) => {
      console.log("handleWsControl:", deviceId, deviceData);
      if (deviceId === sdk.deviceId) {
        // 设备收到控制指令
      }
    };

    const handleWsReport = ({ deviceId, deviceData }: {
      deviceId: string;
      deviceData: Record<string, { Value: unknown; LastUpdate: number }>;
    }) => {
      console.log("handleWsReport:", deviceId, deviceData);
      if (deviceId === sdk.deviceId) {
        // 设备属性上报
        onDeviceDataChange(deviceData);
      }
    };

    const handleWsStatusChange = ({ deviceId, deviceStatus }: {
      deviceId: string;
      deviceStatus: number;
    }) => {
      console.log("handleWsStatusChange:", deviceId, deviceStatus);
      if (deviceId === sdk.deviceId) {
        // 设备在线状态变化（蓝牙设备无效）
        onDeviceStatusChange(deviceStatus);
      }
    };

    // const handleWsEvent = ({ deviceId, deviceData }: {
    //   deviceId: string;
    //   deviceData: 
    // }) => {

    // };

    // 监听wsEventReport事件可以知道发现了哪些设备
    sdk.on('wsEventReport', (data) => {
      console.log('wsEventReport',  data);
      let isHasBrightness = false;
      let brightness = 0;
      const {Payload, deviceId} = data;
      if (deviceId == sdk.deviceId)
      {
        console.log(`发现设备：${deviceId}`);
        const {params} = Payload;
        if ('params' in Payload)
        {
          if ('brightness' in params)
          {
            brightness = params.brightness;
            isHasBrightness = true;
          }
        }
        if (isHasBrightness)
        {
          let val_num = brightness as number;
          // val_num = Math.round(Math.random() * 100) % 0x08;
          console.log(`val_num:${val_num}`);
          let tmp = 0x01; 
          for (let index = 0; index < 3; index++) 
          {
            let id_str = "#power-switch-icon_" + (index + 1);
            const body = document.querySelector(id_str);
            if ((val_num & tmp) != 0)
            {
              body?.setAttribute("class", "power-switch-icon");          
            }
            else
            {
              body?.setAttribute("class", "power-switch-icon off");
            }
            tmp <<= 1;
          }
        }
      }
    });
    
    // 可监听的事件列表参考文档 https://cloud.tencent.com/document/product/1081/67452
    console.log("prepare sdk.on");
    return () => {
      sdk
      .on("wsControl", handleWsControl)
      .on("wsReport", handleWsReport)
      .on("wsStatusChange", handleWsStatusChange);
    };
    
    // return () => {
    //   sdk
    //     .off("wsControl", handleWsControl)
    //     .off("wsReport", handleWsReport)
    //     .off("wsStatusChange", handleWsStatusChange);
    // };
  }, []);

  useEffect(() => {
    // 检查固件更新，若有可升级固件，且设备在线，则弹出提示
    const doCheckFirmwareUpgrade = async () => {
      try {
        const upgradeInfo = await sdk.checkFirmwareUpgrade({
          silent: false, // 设置为 true 则只检查，不弹出提示
        });
        console.log("firmware upgrade info", upgradeInfo);
      } catch (err) {
        console.error("checkFirmwareUpgrade fail", err);
      }
    };

    doCheckFirmwareUpgrade();
  }, []);

  // 设备属性控制
  const doControlDeviceProperty = async (propertyId: string, value: unknown) => {
    // renderHeadPanel();
    // 控制报文
    const payload = {
      [propertyId]: value,
    };
    if (propertyId == 'brightness')
    {
      let val_num = value as number;
      let tmp = 0x01; 
      for (let index = 0; index < 3; index++) 
      {
        let id_str = "#power-switch-body_" + (index + 1);
        const body = document.querySelector(id_str);
        if ((val_num & tmp) != 0)
        {
          body?.setAttribute("class", "power-switch-body");          
        }
        else
        {
          body?.setAttribute("class", "power-switch-body off");
        }
        tmp <<= 1;
      }
    }

    try {
      const res = await sdk.controlDeviceData(payload);
      console.log("[controlDeviceData]", payload, "成功", res);
    } catch (err) {
      console.log("[controlDeviceData]", payload, "失败", err);
    }
  };

  // 一般非在线状态（state.deviceStatus === 0）需要禁止控制
  const disabled = false; // !state.deviceStatus;

  // 指定要展示大按钮的属性标识符，为 null 则取第一个属性
  let headPanelPropertyId: string | null = null;
  if (!headPanelPropertyId
    && state.propertyList.length > 0
    && [
      "int",
      "float",
      "bool",
      "enum",
    ].includes(state.propertyList[0].define.type)
  ) 
  {
    headPanelPropertyId = "brightness";
  }

  // 渲染顶部大按钮
  const renderHeadPanel = () => {
    if (!headPanelPropertyId) return null;

    const headTemplateConfig = state.propertyMap[headPanelPropertyId];
    if (!headTemplateConfig) return null;

    const {
      id,
      define: { type },
    } = headTemplateConfig;
    const value = state.deviceData[id];
    console.log("state.deviceData[id]:", value);

    switch (type) {
      case "int":
      case "float":
        console.log('int/float');
        if (id == "brightness")
        {
          return (
            <HeadBoolPanel
              templateConfig={headTemplateConfig}
              onChange={(value) => doControlDeviceProperty(id, value)}
              value={value as number}
              disabled={disabled}
            />
          );
        }
      default:
        return null;
    }
  };

  // 渲染属性卡片
  const renderProperty = (property: DataTemplateProperty) => {
    switch (property.id) {
      case "name": // 灯位置名称
        break;
      case "color": // 定时
        state.deviceData[property.id] = "";
        break;
      default:
        return; // 其它属性不绘制卡片
    }
    return (
      <PropertyCard
        key={property.id}
        property={property}
        value={state.deviceData[property.id]}
        disabled={disabled}
        onChange={(value) => {
          doControlDeviceProperty(property.id, value);
        }}
      />
    );
  };

  return (
    <div>
      {isStandardBleDevice && (
        <StandardBleConnector familyId={sdk.familyId} deviceId={sdk.deviceId} />
      )}
      <div
        className="device-panel clear-margin"
        style={{ minHeight: `${windowHeight}px` }}
      >
        <DeviceDetailBtn />

        {renderHeadPanel()}

        {state.propertyList.length > 0 && (
          <div className="card-layout">
            {
              state.propertyList.map((property) => renderProperty(property))
            }
          </div>
        )}
      </div>
    </div>
  );
}
